/*
 * D.A.O. for JPA  
 * Created on 6 juin 2013 ( Time 15:03:49 )
 */

package org.demo.site.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.telosys.starterkits.strutsjpa.CoreUtils;
import org.telosys.starterkits.strutsjpa.GenericJpaDao;

import org.demo.site.bean.Site;

public class JpaSiteDAO extends GenericJpaDao<Site, Integer> {

	private static final Predicate[] ap = {};
	
	/**
	 * Constructs a DAO for Site
	 */
	public JpaSiteDAO() {
		super(Site.class);
	}
	
	/**
	 * Search by Site example
	 */
	public List<Site> search(final Site element) {
		final EntityManager em = getEntityManager();
		if ( element != null  ) {
			CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
			CriteriaQuery<Site> criteriaQuery = criteriaBuilder.createQuery(Site.class);
			Root<Site> from = criteriaQuery.from(Site.class);

			List<Predicate> listP = new ArrayList<Predicate>();


			if (CoreUtils.isNotBlank(element.getIdsite())) {
				Predicate predicate = criteriaBuilder.equal(from.get("idsite"), element.getIdsite());
				listP.add(predicate);
			}
			if (CoreUtils.isNotBlank(element.getIdsociete())) {
				Predicate predicate = criteriaBuilder.equal(from.get("idsociete"), element.getIdsociete());
				listP.add(predicate);
			}
			if (CoreUtils.isNotBlank(element.getNomsite())) {
				Predicate predicate = criteriaBuilder.equal(from.get("nomsite"), element.getNomsite());
				listP.add(predicate);
			}
			if (CoreUtils.isNotBlank(element.getAdressesite())) {
				Predicate predicate = criteriaBuilder.equal(from.get("adressesite"), element.getAdressesite());
				listP.add(predicate);
			}
			
			criteriaQuery.where(listP.toArray(ap));
			TypedQuery<Site> tq = em.createQuery(criteriaQuery);
			return tq.getResultList();
		}
		else
		{
    		return this.loadAll();
		}
	}

}